//
//  DDGoodsListViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/16.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDGoodsListViewController.h"
#import "DDGoodsManager.h"
#import "DDGoodsObj.h"
#import "DDGoodsListCollectionCell.h"
#import "DDGoodsListTableCell.h"
#import "MJRefresh.h"
#import "DDGoodsListToolBar.h"
#import "DDGoodsDetailsViewController.h"
#import "DDSortGoodsView.h"

@interface DDGoodsListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource,DDGoodsListToolBarDelegate,UITextFieldDelegate,DDSortGoodsViewDelegate>
@property (strong, nonatomic) DDGoodsManager *manager;
@property (strong, nonatomic) DDGoodsSet *goodsSet;
@property (weak, nonatomic) IBOutlet UICollectionView *goodsCollection;
@property (weak, nonatomic) IBOutlet UITableView *goodsTable;
@property (assign, nonatomic) DingDongListShowType showType;
@property (strong, nonatomic) DDSortGoodsView *sortView;
@property (assign, nonatomic) NSInteger currentPage;
@property (strong, nonatomic) NSString *selectedSortKeyWord;
@end

@implementation DDGoodsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDGoodsManager new];
    [self layoutListView];
}
- (void)layoutListView
{
    self.selectedSortKeyWord = @"";

    [self setRefresh];
    self.goodsCollection.hidden = YES;
    self.goodsTable.hidden = NO;
    self.showType = DingDongListShowTypeTableView;
    UIImage *rightBarImage = [LoadImage(@"goods_collection") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc]initWithImage:rightBarImage style:UIBarButtonItemStylePlain target:self action:@selector(swapListShow)];
    self.navigationItem.rightBarButtonItem = barItem;
    
    //搜索条
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(60, 7, ScreenWidth-120, 30)];
    searchView.backgroundColor = RGBColor(238, 238, 238);
    searchView.layer.cornerRadius = 3.0;
    self.navigationItem.titleView = searchView;
    
    UIButton *searchBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    [searchView addSubview:searchBtn];
    [searchBtn addTarget:self action:@selector(gotoSearch:) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchView);
        make.left.equalTo(searchView).offset(10);
        make.height.equalTo(@25);
        make.right.equalTo(searchView).offset(-40);
    }];
    UIImageView *searchIcon = [[UIImageView alloc]init];
    searchIcon.image = LoadImage(@"goods_search");
    [searchView addSubview:searchIcon];
    [searchIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@20);
        make.centerY.equalTo(searchView);
        make.right.equalTo(searchView).offset(-10);
    }];
    
    DDGoodsListToolBar *toolBar = [[DDGoodsListToolBar alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 45)];
    toolBar.delegate = self;
    [self.view addSubview:toolBar];
}
- (void)gotoSearch:(UIButton *)btn
{
    KKLog(@"1111111");
}
- (void)swapListShow
{
    UIImage *rightBarImage =nil;
    if (self.showType == DingDongListShowTypeTableView) {
        self.goodsCollection.hidden = NO;
        self.goodsTable.hidden = YES;
        rightBarImage = [LoadImage(@"goods_table") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.showType = DingDongListShowTypeCollectionView;
    }else{
        self.goodsCollection.hidden = YES;
        self.goodsTable.hidden = NO;
        rightBarImage = [LoadImage(@"goods_collection") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.showType = DingDongListShowTypeTableView;
    }
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc]initWithImage:rightBarImage style:UIBarButtonItemStylePlain target:self action:@selector(swapListShow)];
    self.navigationItem.rightBarButtonItem = barItem;
}
- (void)setRefresh
{
    weak_Self(self);
    MJRefreshHeader *header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];
    [self.goodsCollection setMj_header:header];
    [self.goodsCollection setMj_footer:footer];
    
    MJRefreshHeader *table_header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    MJRefreshBackNormalFooter *table_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];
    
    [self.goodsTable setMj_header:table_header];
    [self.goodsTable setMj_footer:table_footer];
    [self headerRefresh];
}
- (void)headerRefresh
{
    weak_Self(self);
    if (self.vcType == DingDongGoodsControllerTypeCategory) {
        [self fetchGoodsListPull:YES success:^{
            [weakSelf.goodsCollection.mj_header endRefreshing];
            [weakSelf.goodsTable.mj_header endRefreshing];
        }];
    }else if (self.vcType == DingDongGoodsControllerTypeSearch){
        [self searchGoodsBy:self.searchKeyword sortBy:self.selectedSortKeyWord pull:YES success:^{
            [weakSelf.goodsCollection.mj_footer endRefreshing];
            [weakSelf.goodsTable.mj_footer endRefreshing];
        }];
    }
}
- (void)footerRefresh
{
    weak_Self(self);
    if (self.vcType == DingDongGoodsControllerTypeCategory) {
        [self fetchGoodsListPull:NO success:^{
            [weakSelf.goodsCollection.mj_footer endRefreshing];
            [weakSelf.goodsTable.mj_footer endRefreshing];
        }];
    }else if (self.vcType == DingDongGoodsControllerTypeSearch){
        [self searchGoodsBy:self.searchKeyword sortBy:self.selectedSortKeyWord pull:NO success:^{
            [weakSelf.goodsCollection.mj_footer endRefreshing];
            [weakSelf.goodsTable.mj_footer endRefreshing];
        }];
    }

}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    KKLog(@"1111111");
}
#pragma mark --- ToolBarDelegate
- (void)toolBar:(DDGoodsListToolBar *)bar didSelectIndex:(DingDongSortGoodsType)sortType
{
    KKLog(@"sortType == %ld",sortType);
    if (sortType == DingDongSortGoodsTypeWhole) {
        NSString *defaultSortKey = @"";
        NSArray *sortAry =@[@"Comprehensive Ranking",@"New Product Priority",@"Sort by comments from high to low"];
        if ([self.selectedSortKeyWord isEqualToString:@"good_create_time_desc"]) {
            defaultSortKey = @"New Product Priority";
        }else if ([self.selectedSortKeyWord isEqualToString:@"grade_desc"]) {
            defaultSortKey = @"Sort by comments from high to low";
        }else{
            defaultSortKey = @"Comprehensive Ranking";
        }
        if (!_sortView) {
            self.sortView = [[DDSortGoodsView alloc]initWithFrame:CGRectMake(0, 64+46, ScreenWidth, ScreenHeight-64-46)];
            _sortView.sortAry = sortAry;
            _sortView.defaultSelectSort = defaultSortKey;
            _sortView.delegate = self;
            [self.view addSubview:_sortView];
        }
    }else if (sortType == DingDongSortGoodsTypeVolume){
        self.selectedSortKeyWord = @"buynum_desc";
    }else if (sortType == DingDongSortGoodsTypeLowPrice){
        self.selectedSortKeyWord = @"price_desc";
    }else if (sortType == DingDongSortGoodsTypeHighPrice){
        self.selectedSortKeyWord = @"price_asc";
    }
    
    [self headerRefresh];
}
- (void)sortView:(DDSortGoodsView *)sortView didSelectIndex:(NSInteger)index
{
    if (index == 1) {
        self.selectedSortKeyWord = @"good_create_time_desc";
    }else if (index == 2){
        self.selectedSortKeyWord = @"grade_desc";
    }else if (index == 0){
        self.selectedSortKeyWord = @"";
    }
    [self headerRefresh];
}
- (void)sortViewRemoveFromSuperView
{
    self.sortView = nil;
}
#pragma mark --- 接口
- (void)fetchGoodsListPull:(BOOL)pull success:(void(^)())block
{
    weak_Self(self);
    if (pull) {
        self.currentPage = 1;
    }
    [self showHUD];
    [[self.manager goodsSort:self.category_id byKeywords:self.selectedSortKeyWord pageNumber:self.currentPage pageSize:kPageSize]subscribeNext:^(id x) {
        if (pull) {
            [weakSelf.goodsSet.goodsAry removeAllObjects];
            weakSelf.goodsSet = x;
        }else{
            DDGoodsSet *set = x;
            [weakSelf.goodsSet.goodsAry addObjectsFromArray:set.goodsAry];
        }
        [weakSelf.goodsCollection reloadData];
        [weakSelf.goodsTable reloadData];
        weakSelf.currentPage+=1;
        
    } error:^(NSError *error) {
        
    } completed:^{
        if (block) {
            block();
        }
        [weakSelf hideHUD];
    }];
}
- (void)searchGoodsBy:(NSString *)search sortBy:(NSString *)sort pull:(BOOL)pull success:(void(^)())block
{
    weak_Self(self);
    if (pull) {
        self.currentPage = 1;
    }
    [[self.manager goodsSearchBy:search sort:sort pageNo:self.currentPage size:kPageSize]subscribeNext:^(id x) {
        if (pull) {
            [weakSelf.goodsSet.goodsAry removeAllObjects];
            weakSelf.goodsSet = x;
        }else{
            DDGoodsSet *set = x;
            [weakSelf.goodsSet.goodsAry addObjectsFromArray:set.goodsAry];
        }
        [weakSelf.goodsCollection reloadData];
        [weakSelf.goodsTable reloadData];
        weakSelf.currentPage+=1;

    } error:^(NSError *error) {
        
    } completed:^{
        if (block) {
            block();
        }
    }];
}
#pragma mark --- UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.goodsSet.goodsAry.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"GoodsCell";
    DDGoodsListCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:indentifier forIndexPath:indexPath];
    DDGoodsObj *obj = self.goodsSet.goodsAry[indexPath.row];
    [cell.goodsIcon sd_setImageWithURL:[NSURL URLWithString:obj.thumbnail] placeholderImage:nil];
    cell.goodsNameLbl.text = obj.name;
    cell.goodsPriceLbl.text = [NSString stringWithFormat:@"$%@",obj.price];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDGoodsObj *obj = self.goodsSet.goodsAry[indexPath.row];
    DDGoodsDetailsViewController *vc = [[DDGoodsDetailsViewController alloc]init];
    vc.goods_id =obj.goods_id;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (ScreenWidth-16)/2.0;
    CGFloat height = width+60;
    return (CGSize){width,height};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}

#pragma mark --- UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.goodsSet.goodsAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 135.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"GoodsTableCell";
    
    DDGoodsListTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DDGoodsListTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    DDGoodsObj *obj = self.goodsSet.goodsAry[indexPath.row];
    [cell.goodsIcon sd_setImageWithURL:[NSURL URLWithString:obj.thumbnail] placeholderImage:nil];
    cell.goodsNameLbl.text = obj.name;
    cell.goodsPriceLbl.text = [NSString stringWithFormat:@"$%@",obj.price];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DDGoodsObj *obj = self.goodsSet.goodsAry[indexPath.row];
    DDGoodsDetailsViewController *vc = [[DDGoodsDetailsViewController alloc]init];
    vc.goods_id =obj.goods_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
